package com.example.common.util;

import cn.hutool.core.io.IoUtil;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.errors.MinioException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import lombok.SneakyThrows;

public class JlMinioUtils {
    static String minioUrl = "http://127.0.0.1:9001/";

    static String minioName = "minioadmin";

    static String minioPass = "minioadmin";

    @SneakyThrows
    public static boolean doesObjectExist(String bucketName, InputStream inputStream) {
        try {
            // Initialize Minio client
            MinioClient minioClient = initMinio(minioUrl, minioName, minioPass);

            // Create a temporary file for the input stream
            File tempFile = File.createTempFile("temp", ".tmp");
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            IoUtil.copy(inputStream, outputStream);
            outputStream.close();

            // Check if object exists by comparing content
            GetObjectArgs object = GetObjectArgs.builder().bucket(bucketName).object(tempFile.getName()).build();

            InputStream objectStream = minioClient.getObject(object);
            IoUtil.contentEquals(objectStream, new FileInputStream(tempFile));
            objectStream.close();

            // Delete the temporary file
            tempFile.delete();

            return true;

        } catch (MinioException | IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private static MinioClient initMinio(String minioUrl, String minioName, String minioPass) {
        return MinioClient.builder().endpoint(minioUrl).credentials(minioName, minioPass).build();
    }

}
